package gwtappcontainer.client.apps.videos;

import gwtappcontainer.client.ContainerUtil;
import gwtappcontainer.client.HistoryToken;
import gwtappcontainer.client.IPresenter;
import gwtappcontainer.shared.apps.videos.VideoProp;

import java.util.logging.Logger;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasHTML;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;

public class VideoPresenter implements IPresenter {
	
	interface IView {
		HasHTML getTitleHtml();
		HasHTML getDescHtml();
		HasHTML getVideoFrameHtml();
		HasHTML getAppealHtml();
		Widget asWidget();
	}

	private Logger logger;
	private IView view;
	
	VideoPresenter(IView view, HistoryToken historyToken) {
		this.view = view;
		
		String videoTag = "";
		if (! historyToken.params.isEmpty()) {
			if (historyToken.params.containsKey("tag"))
				videoTag = historyToken.params.get("tag");
		}
		bind(videoTag);
	}
		
	public void bind(String videoTag) {
						
		view.getVideoFrameHtml().setHTML("Fetching video [" + videoTag + "]");	
		
		VideoRpcServiceAsync videoSvc = GWT.create(VideoRpcService.class);
		
		logger = ContainerUtil.getLogger(VideoPresenter.class.getName());
										
		videoSvc.getVideoProp(videoTag, new AsyncCallback<VideoProp>() {

			@Override
			public void onFailure(Throwable caught) {
				String errMessage = "Exception thrown by rpc." + caught.getMessage();
				logger.severe(errMessage + "\n" + caught.toString());			
				Window.alert(errMessage + 
						". Try reloading the page by clicking the refresh button in your browser");
				//to do : change to error dialog box							
			}

			@Override
			public void onSuccess(VideoProp result) {
				
				if (null == result)
					view.getVideoFrameHtml().setHTML("<b>Error</b> - unable to load video");				
				else {
					view.getTitleHtml().setHTML(result.titleHtml);
					view.getDescHtml().setHTML(result.descriptionHtml);
					
					if (result.enabled && ! result.videoFrameHtml.equals("")) {
						view.getVideoFrameHtml().setHTML(result.videoFrameHtml);						
						view.getAppealHtml().setHTML(result.appealHtml);
					} else {
						view.getVideoFrameHtml().setHTML(result.msgWhenVideoNotAvailableHtml);
					}					
				}								
			}
		});					
	}

	@Override
	public String getAppName() {		
		return "Videos";
	}

	@Override
	public void render(HasWidgets container) {
		container.clear();
		container.add(view.asWidget());
		
	}		
}
